package com.resume.service.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.resume.dto.CreateResumeRequest
import com.resume.dto.GenerateResumeRequest
import com.resume.dto.ResumeResponse
import com.resume.entity.Resume
import com.resume.mapper.ResumeMapper
import com.resume.service.ResumeService
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.time.format.DateTimeFormatter

@Service
class ResumeServiceImpl(
    private val resumeMapper: ResumeMapper
) : ResumeService {

    override fun getResumesByUserId(userId: Long, page: Int, size: Int): Any {
        val pageObj = Page<Resume>(page.toLong(), size.toLong())
        val result = resumeMapper.selectPage(
            pageObj,
            QueryWrapper<Resume>().eq("user_id", userId).orderByDesc("created_time")
        )
        
        val resumeList = result.records.map { resume ->
            ResumeResponse(
                id = resume.id!!,
                title = resume.title,
                templateType = resume.templateType,
                content = resume.content,
                previewImage = resume.previewImage,
                status = resume.status,
                createdTime = resume.createdTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: "",
                updatedTime = resume.updatedTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: ""
            )
        }
        
        return mapOf(
            "list" to resumeList,
            "total" to result.total,
            "page" to page,
            "size" to size
        )
    }

    override fun getResume(id: Long, userId: Long): ResumeResponse {
        val resume = resumeMapper.selectOne(
            QueryWrapper<Resume>().eq("id", id).eq("user_id", userId)
        ) ?: throw RuntimeException("简历不存在")

        return ResumeResponse(
            id = resume.id!!,
            title = resume.title,
            templateType = resume.templateType,
            content = resume.content,
            previewImage = resume.previewImage,
            status = resume.status,
            createdTime = resume.createdTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: "",
            updatedTime = resume.updatedTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: ""
        )
    }

    override fun createResume(request: CreateResumeRequest, userId: Long): ResumeResponse {
        val resume = Resume(
            userId = userId,
            title = request.title,
            templateType = request.templateType,
            content = request.content,
            status = 1
        )

        resumeMapper.insert(resume)

        return ResumeResponse(
            id = resume.id!!,
            title = resume.title,
            templateType = resume.templateType,
            content = resume.content,
            previewImage = resume.previewImage,
            status = resume.status,
            createdTime = resume.createdTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: "",
            updatedTime = resume.updatedTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: ""
        )
    }

    override fun updateResume(id: Long, request: CreateResumeRequest, userId: Long): ResumeResponse {
        val existingResume = resumeMapper.selectOne(
            QueryWrapper<Resume>().eq("id", id).eq("user_id", userId)
        ) ?: throw RuntimeException("简历不存在")

        val updatedResume = existingResume.copy(
            title = request.title,
            templateType = request.templateType,
            content = request.content
        )

        resumeMapper.updateById(updatedResume)

        return getResume(id, userId)
    }

    override fun deleteResume(id: Long, userId: Long) {
        val resume = resumeMapper.selectOne(
            QueryWrapper<Resume>().eq("id", id).eq("user_id", userId)
        ) ?: throw RuntimeException("简历不存在")

        resumeMapper.deleteById(id)
    }

    override fun generateResumeByPrompt(request: GenerateResumeRequest, userId: Long): ResumeResponse {
        // TODO: 这里应该调用AI服务生成简历内容
        // 暂时返回一个模拟的简历
        val mockContent = """
        {
            "personal": {
                "name": "AI生成示例",
                "title": "基于您的描述生成",
                "email": "example@email.com",
                "phone": "123-456-7890",
                "summary": "${request.prompt}"
            },
            "experience": [
                {
                    "company": "示例公司",
                    "position": "相关职位",
                    "duration": "2020-至今",
                    "description": "根据您的描述生成的工作经历"
                }
            ]
        }
        """.trimIndent()

        val resume = Resume(
            userId = userId,
            title = "AI生成的简历",
            templateType = request.templateType,
            content = mockContent,
            status = 1
        )

        resumeMapper.insert(resume)

        return ResumeResponse(
            id = resume.id!!,
            title = resume.title,
            templateType = resume.templateType,
            content = resume.content,
            previewImage = resume.previewImage,
            status = resume.status,
            createdTime = resume.createdTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: "",
            updatedTime = resume.updatedTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: ""
        )
    }

    override fun generateResumeFromTemplate(file: MultipartFile, userId: Long): ResumeResponse {
        // TODO: 解析上传的文件并生成简历
        // 暂时返回一个模拟的简历
        val mockContent = """
        {
            "personal": {
                "name": "模板生成示例",
                "title": "从上传文件解析",
                "email": "template@email.com"
            }
        }
        """.trimIndent()

        val resume = Resume(
            userId = userId,
            title = "从模板生成的简历",
            templateType = "uploaded",
            content = mockContent,
            status = 1
        )

        resumeMapper.insert(resume)

        return ResumeResponse(
            id = resume.id!!,
            title = resume.title,
            templateType = resume.templateType,
            content = resume.content,
            previewImage = resume.previewImage,
            status = resume.status,
            createdTime = resume.createdTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: "",
            updatedTime = resume.updatedTime?.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ?: ""
        )
    }

    override fun exportResume(id: Long, format: String, userId: Long): ResponseEntity<ByteArray> {
        val resume = getResume(id, userId)
        
        // TODO: 实现真正的文件导出
        val mockContent = "简历导出内容 - ${resume.title}".toByteArray()
        
        val headers = HttpHeaders()
        when (format.lowercase()) {
            "word" -> {
                headers.contentType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                headers.setContentDispositionFormData("attachment", "${resume.title}.docx")
            }
            "pdf" -> {
                headers.contentType = MediaType.APPLICATION_PDF
                headers.setContentDispositionFormData("attachment", "${resume.title}.pdf")
            }
            "md" -> {
                headers.contentType = MediaType.TEXT_PLAIN
                headers.setContentDispositionFormData("attachment", "${resume.title}.md")
            }
            else -> throw RuntimeException("不支持的导出格式")
        }
        
        return ResponseEntity.ok()
            .headers(headers)
            .body(mockContent)
    }
} 